package com.mg.service.impl;

import com.mg.common.Constants;
import com.mg.service.SmsService;
import com.mg.sms.Message;
import com.mg.utils.HttpUtil;
import com.mg.utils.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Map;

/**
 * @author mg1213
 * 2018/3/28
 **/
@Service
public class SmsServiceImpl implements SmsService {
    private Logger logger = LogManager.getLogger(SmsServiceImpl.class.getName());
    @Value("${smsApiKey}")
    private String smsApiKey;
    @Value("${expiryTime}")
    private int expiryTime;
    @Value("${api01Url}")
    private String api01Url;

    @Override
    public boolean sendMessage(String code, String mobile) {
        return this.sendMessage(code, mobile, expiryTime);
    }

    @Override
    public boolean sendMessage(String code, String mobile, int expiryTime) {
        boolean flag = true;
        // 参数类
        Message message = new Message();
        message.setApikey(smsApiKey.trim());

        // 设置手机号码 此处只能设置一个手机号码
        message.setMobile(mobile);
        // 设置内容
        message.setContent("您的验证码是" + code + "，在" + expiryTime + "分钟内有效。如非本人操作请忽略本短信。");
        // 设置扩展号
        message.setExno("11");
        //业务类型
        message.setSvrtype("SMS001");

        // 返回的平台流水编号等信息
        StringBuffer msgId = new StringBuffer();
        // 发送短信

        try {
            message.setContent(URLEncoder.encode(message.getContent(), "GBK"));

            Map<String, Object> result = HttpUtil.jsonPost(api01Url.trim(), message);
            int resultCode = (int) result.get("code");
            if (resultCode == Constants.HTTP_SUCCESS) {
                if (0 != (int) result.get("result")) {
                    flag = false;
                    logger.error("send message error :{}", JsonUtils.toJson(result));
                }

            } else {
                flag = false;
                logger.error("send message error :{}", JsonUtils.toJson(result));
            }

        } catch (Exception e) {
            flag = false;
            logger.error("send message error :{}", e);
        }
        return flag;
    }

    public static void main(String[] args) {
        SmsServiceImpl smsService = new SmsServiceImpl();
        smsService.sendMessage("WE2311","108");
    }
}
